package cn.ecnu.service.forum.impl;

import cn.ecnu.mapper.forum.CommentMapper;
import cn.ecnu.mapper.forum.LikeMapper;
import cn.ecnu.mapper.forum.PostMapper;
import cn.ecnu.pojo.User;
import cn.ecnu.pojo.forum.Comment;
import cn.ecnu.pojo.forum.Like;
import cn.ecnu.pojo.forum.Post;
import cn.ecnu.service.forum.LikeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class LikeServiceImpl implements LikeService {

    @Resource
    private LikeMapper likeMapper;

    @Resource
    private PostMapper postMapper;

    @Resource
    private CommentMapper commentMapper;

    @Override
    public int likeAnType(Integer userId, Integer typeId, Integer flag) {
        int result = 0;
        if (flag == 0) {
            // 点赞一个post
            Post post = postMapper.getPostById(typeId);
            post.setHot(post.getHot() + 10); post.setLikeCount(post.getLikeCount() + 1);
            postMapper.updatePostById(post); // 更新post
        } else {
            Comment comment = commentMapper.getCommentById(typeId);
            comment.setLikeCount(comment.getLikeCount() + 1);
            commentMapper.updateCommentById(comment);
        }
        result = likeMapper.insertLike(new Like(null, typeId, userId, new Date(), flag));
        return result;
    }

    @Override
    public int dislikeAnType(Integer userId, Integer typeId, Integer flag) {
        int result = 0;
        if (flag == 0) {
            // 点赞一个post
            Post post = postMapper.getPostById(typeId);
            post.setHot(post.getHot() - 10); post.setLikeCount(post.getLikeCount() - 1);
            postMapper.updatePostById(post); // 更新post
        } else {
            Comment comment = commentMapper.getCommentById(typeId);
            comment.setLikeCount(comment.getLikeCount() + 1);
            commentMapper.updateCommentById(comment);
        }
        result = likeMapper.deleteLikeByUidAndTypeId(userId, typeId, flag);
        return result;
    }

    // 获得一个类型的点赞用户表
    @Override
    public List<User> getLikeUserOfType(Integer typeId, Integer flag) {
        if (flag == 0) return likeMapper.getLikeUserByPostId(typeId);
        else if (flag == 1) return likeMapper.getLikeUserByCommentId(typeId);
        return null;
    }

    @Override
    public List<Post> getLikePostOfUser(Integer userId) {
        return likeMapper.getPostByUserLike(userId);
    }

    // 用户是否点赞了某一个内容
    @Override
    public boolean isLikeType(Integer userId, Integer typeId, Integer flag) {
        List<Like> likes = null;
        if (flag == 0) {
            likes = likeMapper.getLikeByDoubleIdForPost(userId, typeId);
        }
        else if (flag == 1) {
            likes = likeMapper.getLikeByDoubleIdForComment(userId, typeId);
        }
        return likes != null && likes.size() > 0;
    }
}
